const { Router } = require('express');
const logger = require('../utils/logger');
const Resp = require('../model/resp');
const { validator, ValidQueue } = require('../midwares/valider');
const Aftersale = require('../model/aftersale');
const { decryptToken } = require('../utils/auth');

const router = Router();

/**
 * 获取当前用户全部售后
 */
router.get('/', ValidQueue(
  [
    validator.header('satoken')
    .custom(async (value)=>{
      const payloads = await decryptToken(value);
      const info = JSON.parse(payloads.loginId);
      logger.info(`info: ${JSON.stringify(info)}`);
      const role = info.role;
      if (role!=1) {
        throw new Error('Permission denied');
      }
    })
  ]
),async (req, res, next)=>{
  logger.debug(`satoken: ${req.headers.satoken}`);
  const {loginId} = await decryptToken(req.headers.satoken);
  const info = JSON.parse(loginId);
  const {id: cid} = info;

  logger.debug(`id: ${cid}`);
  
  const records = await Aftersale.findAll({
    attributes: ['aid', 'title', 'classify', 'gname', 'oid', 'atime', 'astate', 'updatedAt'],
    where: {
      cid: cid,
      visible: 1
    }
  });
  logger.debug(`${records}`);
  if (records.length === 0) {
    return res.json(Resp.ok("查询成功，没有售后申请", 322, records)).end();
  }
  res.json(Resp.ok("查询成功", 321, records)).end();
});

/**
 * 商家获取全部售后
 */
router.get('/getall', ValidQueue(
  validator.header('satoken')
  .custom(async (value)=>{
    const payloads = await decryptToken(value);
    const info = JSON.parse(payloads.loginId);
    logger.info(`info: ${JSON.stringify(info)}`);
    const role = info.role;
    if (role!=0) {
      throw new Error('Permission denied');
    }
  })
),async (req, res, next)=>{
  //logger.debug(`satoken: ${req.headers.satoken}`);
  
  const records = await Aftersale.findAll({
    attributes: ['aid', 'title', 'classify', 'gname', 'oid', 'atime', 'astate', 'updatedAt']
  });
  logger.debug(`${records}`);
  if (records.length === 0) {
    return res.json(Resp.ok("查询成功，没有售后申请", 1, records)).end();
  }
  res.json(Resp.ok("查询成功", 2, records)).end();
});

module.exports = router;
